package com.jky.filesystem;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.rpc.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.util.*;

public class ServiceAbility extends Ability {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "FileAbilityLOG");

    private final MyRemote remote = new MyRemote();

    @Override
    public void onStart(Intent intent) {
        HiLog.error(LABEL_LOG, "onStart");
        super.onStart(intent);
    }

    class MyRemote extends RemoteObject implements IRemoteBroker {
        private static final int ERROR = 1;
        private static final int REQUEST_SHARE_FILE = 1003;

        MyRemote() {
            super("ServiceRemote");
        }

        @Override
        public IRemoteObject asObject() {
            return this;
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
            HiLog.info(LABEL_LOG,"java接收："+code);
            if(code == REQUEST_SHARE_FILE){
                HiLog.info(LABEL_LOG,"getBundleName："+getBundleName());
                HiLog.info(LABEL_LOG,"RemoteAbility："+RemoteAbility.class.getName());
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName(RemoteAbility.class.getName())
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            }
            else {
                Map<String, Object> result = new HashMap<>();
                result.put("abilityError", ERROR);
                reply.writeString(ZSONObject.toZSONString(result));
                return false;
            }
            return true;
        }
    }


    @Override
    public void onBackground() {

    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.error(LABEL_LOG, "ServiceAbility::onStop");
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        HiLog.error(LABEL_LOG,"onConnect" + (intent != null));
        super.onConnect(intent);
        return remote.asObject();
    }

    @Override
    public void onDisconnect(Intent intent) {
        HiLog.error(LABEL_LOG,"onDisconnect" + (intent != null));
    }
}